import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:getx_learn/app/modules/weichat_post/api/index.dart';
import 'package:getx_learn/app/modules/weichat_post/entity/index.dart';

class TimelineController extends GetxController
    with GetSingleTickerProviderStateMixin {
  final count = 0.obs;

  // 用户资料
  UserModel? user;

  // 时间线
  final items = <TimelineModel>[].obs;

  // 动画控制器(需要使用 GetSingleTickerProviderStateMixin 来帮助动画生命周期自动管理)
  late AnimationController animationController;

  // 动画 tween
  late Animation<double> sizeTween;

  // 滚动控制器
  final ScrollController scrollController = ScrollController();
  // appbar 背景色
  Rx<Color?> appBarColor = Rx(null);

  // 当前操作的 item
  Rx<TimelineModel?> currentItem = Rx(null);

  // 是否显示评论输入框
  final isShowInput = false.obs;

  // 是否展示表情列表
  final isShowEmoji = false.obs;

  // 是否输入内容
  final isInputWords = false.obs;

  // 评论输入值
  final TextEditingController textCommentEditingController =
      TextEditingController();

  // 输入框焦点
  final FocusNode focusNode = FocusNode();

  // 键盘的高度
  final double keyboardHeight = 200;

  // StreamSubscription? _streamSubscription;

  final isShowSystemKeyboard = true.obs;

  Future _loadData() async {
    var result = await TimelineApi.pageList();

    items.value = result;
  }

  void build(BuildContext context) {}

  @override
  void onInit() {
    super.onInit();
    // var keyboardVisibilityController = KeyboardVisibilityController();

    // _streamSubscription =
    //     keyboardVisibilityController.onChange.listen((bool isVisible) {
    //   if (isVisible && isShowEmoji.value == true) {
    //     // 隐藏键盘
    //     FocusManager.instance.primaryFocus?.unfocus();
    //   }
    //   print("keyboard is visible ${isVisible}");
    // });

    // 设置用户资料
    user = UserModel(
      nickname: "Hzh",
      avator:
          "https://ducafecat.oss-cn-beijing.aliyuncs.com/ducafecat/logo-500.png",
      cover:
          "https://ducafecat-pub.oss-cn-qingdao.aliyuncs.com/cover/activeprogrammer.jpg",
    );
    _loadData();
    animationController = AnimationController(
        vsync: this,
        duration: Duration(
          milliseconds: 500,
        ));

    sizeTween = Tween(begin: 0.0, end: 200.0).animate(
      CurvedAnimation(
        parent: animationController,
        curve: Curves.easeInOut,
      ),
    );

    // 监听 ScrollController 的滚动高度
    scrollController.addListener(() {
      // 滚动条超过 200 时，开始渐变
      if (scrollController.position.pixels > 200) {
        // 透明度系数
        double opacity = (scrollController.position.pixels - 200) / 100;
        if (opacity < 0.85) {
          appBarColor.value = Colors.black.withOpacity(opacity);
        }
      } else {
        appBarColor.value = null;
      }
    });

    textCommentEditingController.addListener(() {
      isInputWords.value = textCommentEditingController.text.isNotEmpty;
    });
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    animationController.dispose();
    scrollController.dispose();
    textCommentEditingController.dispose();
    focusNode.dispose();
    super.onClose();
    // _streamSubscription?.cancel();
  }

  void increment() => count.value++;

  // 点赞操作
  bool onLine() {
    if (currentItem.value == null) return false;

    currentItem.value?.isLike = !(currentItem.value?.isLike ?? false);

    currentItem.value = currentItem.value;

    // 执行请求
    TimelineApi.like(currentItem.value!.id!);

    return true;
  }
}
